<template>
  <div class="login-wrap">
    <div class="main">
      <div class="left">
        <img src="" alt="">
      </div>
      <div class="right">
        <div class="login-form">
          <el-form ref="loginFormRef" size="large" autocomplete="off" :model="formData" :rules="formDataRules">
            <el-form-item>
              <h1>登录</h1>
            </el-form-item>
            <el-form-item prop="username">
              <el-input name="username" :prefix-icon="User" placeholder="请输入用户名" v-model="formData.username"></el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input name="password" :prefix-icon="Lock" type="password" placeholder="请输入密码"
                v-model="formData.password"></el-input>
            </el-form-item>
            <el-form-item class="flex">
              <div class="flex">
                <el-checkbox>记住我</el-checkbox>
              </div>
            </el-form-item>
            <!-- 登录按钮 -->
            <el-form-item>
              <el-button class="button" type="primary" auto-insert-space @click="onLogin">登录</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>

  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import { useRouter } from "vue-router"
import { ElMessage, ElMessageBox } from "element-plus";
import { login } from './api.js'
window.localStorage.removeItem('login_username')
window.localStorage.removeItem('login_token')
window.localStorage.removeItem('login_role')

const router = useRouter()

const formData = reactive({
  username: '',
  password: '',
  rePassword: ''
})


const formDataRules = reactive({
  username: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
  ],
  password: [
      { required: true, message: '请输入密码', trigger: 'blur' },
  ]
})

const loginFormRef = ref(null)

const loginUser = async () => {
  let result = await login({
    username: formData.username,
    password: formData.password
  })
  let message = result.message
  if (result.status == 0) {
    window.localStorage.setItem('login_username', formData.username)
    window.localStorage.setItem('login_token', result.data.token)
    window.localStorage.setItem('login_role', result.data.role)
    ElMessage.success('登录成功!')
    setTimeout(()=>{
      router.push({
        path: '/custom/index'
      })
    }, 2000)
  } else {
    ElMessage.error(message ? message : '登录失败!')
  }
}
const onLogin = () => {
  if (!loginFormRef) return
  loginFormRef.value.validate((valid) => {
    if (valid) {
      loginUser()
    }
  })
}
</script>
<style lang="scss" scoped>
.main {
  display: flex;
  height: 100vh;
  align-items: center;
  .left {
    flex: 1;
    text-align: center;

  }
  .right {
    flex: 1;
    align-self: center;
    .login-form {
      width: 260px;
    }
  }

}
</style>